/**
 * 
 */
package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.entities.ShareINode;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.model.response.INodeShare;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class ShareINodeDao extends BaseDao implements IShareINodeDao {

	public final static String LOG_TAG = "ShareINodeDao";

	@Override
	public void insertFolderOrFile(INodeShareV2 nodeShare) {
		// TODO Auto-generated method stub
		try {
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, nodeShare.getNodeId());
			cv.put(IBaseDao.owner_by, nodeShare.getOwnerId());
			cv.put(IBaseDao.inodeid, nodeShare.getNodeId());
			cv.put(IBaseDao.file_name, nodeShare.getName());
			cv.put(IBaseDao.modifiedAt, nodeShare.getModifiedAt());
			cv.put(IBaseDao.modified_by, nodeShare.getModifiedBy());
			cv.put(IBaseDao.ownerName, nodeShare.getOwnerName());
			cv.put(IBaseDao.ownerId, nodeShare.getOwnerId());
			cv.put(IBaseDao.file_size, nodeShare.getSize());
			cv.put(IBaseDao.status, nodeShare.getStatus());
			cv.put(IBaseDao.type, nodeShare.getType());
			cv.put(IBaseDao.sharedUserId, nodeShare.getSharedUserId());
			cv.put(IBaseDao.sharedUserLoginName,
					nodeShare.getSharedUserLoginName());
			cv.put(IBaseDao.sharedUserName, nodeShare.getSharedUserName());
			cv.put(IBaseDao.sharedUserType, nodeShare.getSharedUserType());
			cv.put(IBaseDao.trans_status, 0);
			// cv.put(IBaseDao.fileIcon, nodeShare.getThumbnailURL());
			cv.put(IBaseDao.isSync, 0);
			this.getDb().insert(TABLE_NAME, null, cv);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"insertFolderOrFile is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateFolderOrFile(INodeShare nodeShare) {
		// TODO Auto-generated method stub
		try {
			if (null != nodeShare) {
				long fileSize = nodeShare.getSize();
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set " + IBaseDao.file_size
								+ "=? where " + inodeid + " = ? and "
								+ IBaseDao.ownerId + "=?",
						new String[] { "" + fileSize, nodeShare.getiNodeId()+"",
								nodeShare.getOwnerId()+"" });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateFolderOrFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public void insertFolderOrFile(ShareINode nodeShare) {
		try {
			this.getDb().insert(TABLE_NAME, null, nodeShare.toContentValues());
		} catch(Exception e) {
			LogUtil.e(LOG_TAG,
					"Insert FolderOrFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public void updateFolderOrFile(ShareINode nodeShare) {
		String whereClause = IBaseDao.id + "=? and " 
						+ IBaseDao.owner_by + "=? and "
						+ IBaseDao.sharedUserId + "=?";
		
		String[] whereArgs = new String[] {
				nodeShare.getId(), 
				nodeShare.getOwnerId(), 
				nodeShare.getSharedUserId()+""};
		
		this.getDb().update(TABLE_NAME, 
				nodeShare.toContentValues(), 
				whereClause, 
				whereArgs);
	}
	
	public void deleteFolderOrFile(String nodeId, String ownerId) {
		String whereClause = IBaseDao.id + "=? and " 
				+ IBaseDao.owner_by + "=? and "
				+ IBaseDao.sharedUserId + "=?";

		String[] whereArgs = new String[] {
				nodeId, 
				ownerId, 
				ShareDriveApplication.getInstance().getWnerID()};

		this.getDb().delete(TABLE_NAME, whereClause, whereArgs);
	}
	
	@Override
	public List<FileFolderInfo> getAllMySharedShip() {
		List<FileFolderInfo> nodeList = new ArrayList<FileFolderInfo>();
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("select * from ").append(TABLE_NAME);
			sb.append(" where ");
			sb.append(IBaseDao.sharedUserId).append("=?");
			String[] whereArgument = {ShareDriveApplication.getInstance().getWnerID()};
			
			Cursor cursor = this.getDb().rawQuery(sb.toString(), whereArgument);
			if(cursor != null) {
				while (cursor.moveToNext()) {
					ShareINode node = new ShareINode();
					node.fromCursor(cursor);
					nodeList.add(node);
				}
				cursor.close();
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "getFileList is fail:" + e.getLocalizedMessage());
		}
		return nodeList;
	}
	
	@Override
	public ShareINode getShareINode(String resId, String ownerId) {
		ShareINode shareInode = null;
		try {
			if (StringUtil.isNotBlank(resId) && StringUtil.isNotBlank(ownerId)) {
				StringBuilder sb = new StringBuilder();
				sb.append("select * from ").append(TABLE_NAME);
				sb.append(" where ");
				sb.append(IBaseDao.id).append("=?").append(" and ");
				sb.append(IBaseDao.owner_by).append("=?").append(" and ");
				sb.append(IBaseDao.sharedUserId).append("=?");
				String[] whereArgument = {resId, ownerId, ShareDriveApplication.getInstance().getWnerID()};
				
				Cursor cursor = this.getDb().rawQuery(sb.toString(), whereArgument );
				if(cursor != null) {
					if (cursor.moveToFirst()) {
						shareInode = new ShareINode();
						shareInode.fromCursor(cursor);
					}
					cursor.close();
				}
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "getFileList is fail:" + e.getLocalizedMessage());
		}
		return shareInode;
	}
	
	public ShareINode getShareINode(INodeShareV2 nodeShare) {
		return getShareINode(""+nodeShare.getNodeId(), ""+nodeShare.getOwnerId());
	}

	@Override
	public List<FileFolderInfo> getFileList(String folderId, String ownerId2) {
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		try {
			if (null != folderId) {
				String strSQL = "select * from " + TABLE_NAME +" where "+ IBaseDao.sharedUserId + " =?"
								+ " Order by modified_at desc";
				String[] where = {ShareDriveApplication.getInstance().getWnerID()};
				Cursor cursor = this.getDb().rawQuery(strSQL, where );
				if (false == cursor.moveToFirst()) {
					return fileFolderInfoList;
				}
				do {
					FileFolderInfo fileFolderInfo = new FileFolderInfo();
					fetchCarsorToFileFolderInfoList(fileFolderInfo,cursor,fileFolderInfoList);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList is fail:" + e.getLocalizedMessage());
		}
		return fileFolderInfoList;
	}

	@Override
	public List<FileFolderInfo> getFileList(String folderId, String ownerId2,
			String des, String orderBy) {
		List<FileFolderInfo> fileInfoList = new ArrayList<FileFolderInfo>();
		try {
			if (null != folderId) {
				Cursor cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where "+ IBaseDao.sharedUserId + " =? and "
								+ IBaseDao.type + " = ? Order by " + orderBy
								+ " " + des, new String[] { ShareDriveApplication.getInstance().getWnerID(),  "1"});
				if (false == cursor.moveToFirst()) {
					return fileInfoList;
				}
				do {
					FileInfo fileInfo = new FileInfo();
					fetchCarsorToFileFolderInfoList(fileInfo,cursor,fileInfoList);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList is fail:" + e.getLocalizedMessage());
		}
		return fileInfoList;
	}

	@Override
	public List<FileFolderInfo> getFolderList(String folderId, String ownerId2,
			String des, String orderBy) {

		List<FileFolderInfo> folderInfoList = new ArrayList<FileFolderInfo>();
		try {
			if (null != folderId) {
				Cursor cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where " + IBaseDao.sharedUserId + " =? and "
								+ IBaseDao.type + " = ? Order by " + orderBy
								+ " " + des, new String[] {ShareDriveApplication.getInstance().getWnerID(), "0" });
				if (false == cursor.moveToFirst()) {
					return folderInfoList;
				}
				do {
					FolderInfo folderInfo = new FolderInfo();
					fetchCarsorToFileFolderInfoList(folderInfo,cursor,folderInfoList);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"getFolderList is fail:" + e.getLocalizedMessage());
		}
		return folderInfoList;
	}
	
	private FileFolderInfo fetchCarsorToFileFolderInfoList(FileFolderInfo folderInfo, Cursor cursor, List<FileFolderInfo> folderInfoList) {
		folderInfo = fentchCursorToObject(folderInfo, cursor);
		if (!"0".equals(folderInfo.getiNodeId())) {
			folderInfoList.add(folderInfo);
		}
		return folderInfo;
	}

	private FileFolderInfo fentchCursorToObject(FileFolderInfo folderInfo, Cursor cursor) {
		folderInfo.setId(cursor.getString(cursor.getColumnIndex(inodeid)));
		folderInfo.setiNodeId(cursor.getString(cursor.getColumnIndex(inodeid)));
		folderInfo.setModifiedAt(cursor.getLong(cursor
				.getColumnIndex(modifiedAt)));
		folderInfo.setModifiedBy(cursor.getString(cursor
				.getColumnIndex(modified_by)));
		folderInfo.setName(cursor.getString(cursor.getColumnIndex(file_name)));
		folderInfo.setOwnerBy(cursor.getString(cursor.getColumnIndex(ownerId)));
		folderInfo.setOwnerName(cursor.getString(cursor
				.getColumnIndex(ownerName)));
		folderInfo
				.setToleName(cursor.getString(cursor.getColumnIndex(toleName)));
		folderInfo.setShareDepartment(cursor.getString(cursor
				.getColumnIndex(shareDepartment)));
		folderInfo.setSharedUserId(cursor.getInt(cursor
				.getColumnIndex(sharedUserId)));
		folderInfo.setSharedUserLoginName(cursor.getString(cursor
				.getColumnIndex(sharedUserLoginName)));
		folderInfo.setSharedUserName(cursor.getString(cursor
				.getColumnIndex(sharedUserName)));
		folderInfo.setIsFile(Integer.parseInt(cursor.getString(cursor
				.getColumnIndex(type))));
		folderInfo.setSharedUserType(cursor.getString(cursor
				.getColumnIndex(sharedUserType)));
		folderInfo.setStatus(cursor.getString(cursor.getColumnIndex(static_status)));
		folderInfo
				.setRoleName(cursor.getString(cursor.getColumnIndex(roleName)));
		folderInfo.setSize(cursor.getLong(cursor.getColumnIndex(file_size)));
		folderInfo.setSync(cursor.getInt(cursor.getColumnIndex(isSync)) == 1);
		folderInfo.setTransStatus(cursor.getInt(cursor
				.getColumnIndex(trans_status)));
		folderInfo.setThumbnailURL(cursor.getString(cursor
				.getColumnIndex(fileIcon)));
		return folderInfo;
	}
	
	@Override
	public void deleteFileOrFolder(String folderId, String ownerId) {
		try {
			this.getDb().execSQL(
					"delete from " + TABLE_NAME + " where id = ? and "+ IBaseDao.sharedUserId + " =? and "
							+ owner_by + " =?",
					new String[] { folderId,ShareDriveApplication.getInstance().getWnerID(), ownerId });
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"deleteFileOrFolder is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateTransStatus(int status, String folderId, String ownerBy) {
		// TODO Auto-generated method stub
		try {
			String where = inodeid + "=? and " + owner_by + "=? and "+ IBaseDao.sharedUserId + " =?";
			String[] whereValue = { folderId, ownerBy, ShareDriveApplication.getInstance().getWnerID()};
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.trans_status, status);
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateTransStatus is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public int updateSyncStatuc(int syncStatus, String folderId, String ownerBy) {
		// TODO Auto-generated method stub
		try {
			String where = inodeid + " = ? and " + owner_by + " = ? and "+ IBaseDao.sharedUserId + " =?";
			String[] whereValue = { folderId, ownerBy, ShareDriveApplication.getInstance().getWnerID() };
			ContentValues cv = new ContentValues();
			cv.put(isSync, syncStatus);
			return this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateSyncStatuc is fail:" + e.getLocalizedMessage());
		}
		return -1;
	}

	@Override
	public long getLastUpdateTime(Context context, String objectId) {
		// TODO Auto-generated method stub

		long lastUpdateTime = 0;
		try {
			if (null != objectId) {
				String[] whereValue = { objectId,
						PublicTools.getOwnerId(context)};
				Cursor cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where " 
										+ inodeid + " = ? and "+ IBaseDao.sharedUserId + " =?",
										whereValue);
				if (cursor.moveToFirst()) {
					lastUpdateTime = cursor.getLong(cursor
							.getColumnIndex(last_refresh_time));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"getLastUpdateTime is fail:" + e.getLocalizedMessage());
		}
		return lastUpdateTime;
	}

	@Override
	public void updateLastUpdateTime(String objectId) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateFile(INodeShareV2 nodeShare, boolean issync) {
		// TODO Auto-generated method stub
		try {
			String where = inodeid + "=? and " + ownerId + "=? and "+ IBaseDao.sharedUserId + " =?";
			String[] whereValue = { nodeShare.getNodeId().toString(),
					"" + nodeShare.getOwnerId(), ShareDriveApplication.getInstance().getWnerID() };
			ContentValues cv = new ContentValues();
			// cv.put(IBaseDao.id, nodeShare.getId());
			cv.put(IBaseDao.owner_by, nodeShare.getOwnerId());
			cv.put(IBaseDao.inodeid, nodeShare.getNodeId());
			cv.put(IBaseDao.file_name, nodeShare.getName());
			cv.put(IBaseDao.modifiedAt, nodeShare.getModifiedAt());
			cv.put(IBaseDao.modified_by, nodeShare.getModifiedBy());
			cv.put(IBaseDao.ownerName, nodeShare.getOwnerName());
			cv.put(IBaseDao.ownerId, nodeShare.getOwnerId());
			cv.put(IBaseDao.file_size, nodeShare.getSize());
			cv.put(IBaseDao.status, nodeShare.getStatus());
			cv.put(IBaseDao.type, nodeShare.getType());
			cv.put(IBaseDao.sharedUserId, nodeShare.getSharedUserId());
			cv.put(IBaseDao.sharedUserLoginName,
					nodeShare.getSharedUserLoginName());
			cv.put(IBaseDao.sharedUserName, nodeShare.getSharedUserName());
			cv.put(IBaseDao.sharedUserType, nodeShare.getSharedUserType());
			// cv.put(IBaseDao.trans_status, 0);
			// cv.put(IBaseDao.isSync, 0);
			if (issync) {
				cv.put(IBaseDao.isSync, 0);
			}
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateFile is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public FileFolderInfo getFileById(String fileID, String ownerBy) {
		FileFolderInfo fileFolderInfo = null;
		Cursor cursor = null;
		try {
			if (null != fileID) {
				String[] whereValue = { fileID, ownerBy, ShareDriveApplication.getInstance().getWnerID() };
				cursor = this.getDb().rawQuery(
						"select * from " + TABLE_NAME + " where " + inodeid
								+ " = ? and " + owner_by + " = ? and "+ IBaseDao.sharedUserId + " =?",
								whereValue);
				if (false == cursor.moveToFirst()) {
					return fileFolderInfo;
				}
				fileFolderInfo = new FileFolderInfo();
				fileFolderInfo = fentchCursorToObject(fileFolderInfo, cursor);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileById is fail:" + e.getLocalizedMessage());
		} finally {
			if(cursor != null && !cursor.isClosed() ) {
				cursor.close();
			}
		}
		return fileFolderInfo;
	}

	@Override
	public void updateLocalPath(String fileId, String ownerBy, String localPath) {
		// TODO Auto-generated method stub
		try {
			if (null != fileId) {
				this.getDb().execSQL(
						"update  " + TABLE_NAME + " set " + IBaseDao.local_path
								+ " = ? where " + inodeid + " = ? and "
								+ owner_by + "=? and "+ IBaseDao.sharedUserId + " =?",
						new String[] { localPath, fileId, ownerBy, ShareDriveApplication.getInstance().getWnerID() });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG,
					"updateLocalPath is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void deleteAll() {
		// TODO Auto-generated method stub
		try {
			this.getDb().delete(TABLE_NAME, null, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteAll is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void insertOrUpdateShareFolder(Context context, String folderId,
			String ownerId, FolderInfo nodeShare) {
		// TODO Auto-generated method stub
		try {
			String where = IBaseDao.inodeid + "=? and " + IBaseDao.sharedUserId
					+ "=?";
			String[] whereValue = { nodeShare.getiNodeId(),
					nodeShare.getOwnerId() };
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, nodeShare.getiNodeId());
			cv.put(IBaseDao.owner_by, nodeShare.getOwnerId());
			cv.put(IBaseDao.inodeid, nodeShare.getiNodeId());
			cv.put(IBaseDao.file_name, nodeShare.getName());
			cv.put(IBaseDao.modifiedAt, nodeShare.getModifiedAt());
			cv.put(IBaseDao.modified_by, nodeShare.getModifiedBy());
			cv.put(IBaseDao.ownerName, nodeShare.getOwnerName());
			cv.put(IBaseDao.ownerId, nodeShare.getOwnerId());
			cv.put(IBaseDao.file_size, nodeShare.getSize());
			cv.put(IBaseDao.static_status, nodeShare.getStatus());
			cv.put(IBaseDao.type, nodeShare.getType());
			cv.put(IBaseDao.sharedUserId, nodeShare.getSharedUserId());
			cv.put(IBaseDao.sharedUserLoginName,
					nodeShare.getSharedUserLoginName());
			cv.put(IBaseDao.sharedUserName, nodeShare.getSharedUserName());
			cv.put(IBaseDao.sharedUserType, nodeShare.getSharedUserType());
			cv.put(IBaseDao.last_refresh_time, nodeShare.getLastRefreshTime());

			FileFolderInfo infors = DAOFactory.instance(context)
					.getShareINodeDao().getFileById(folderId, ownerId);
			if (null == infors) {
				cv.put(IBaseDao.trans_status, Constant.DOWNLOAD_NON_UPDATE_DB);
				cv.put(IBaseDao.isSync, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
				this.getDb().insert(TABLE_NAME, null, cv);
			} else {
				this.getDb().update(TABLE_NAME, cv, where, whereValue);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateFile is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public long getLastUpdateTime(String objectId) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void cleanCatch() {
		try {
			String currentUserId = ShareDriveApplication.getInstance()
					.getWnerID();
			if (currentUserId == null || currentUserId.equals("")) {
				return;
			}
			ContentValues values = new ContentValues();
			values.put(IBaseDao.local_path, "");
			values.put(IBaseDao.trans_status, Constant.DOWNLOAD_NON_UPDATE_DB);
			values.put(IBaseDao.isSync, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
			String whereClause = IBaseDao.sharedUserId + " =?";
			String[] whereArgs = { currentUserId };
			this.getDb().update(TABLE_NAME, values, whereClause, whereArgs);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "cleanCatch is fail:" + e.getLocalizedMessage());
		}
	}
}
